<template>
  <div>
    <el-upload
      class="image-uploader"
      ref="uploader"
      list-type=""
      action="//up.qbox.me/"
      :limit='1'
      :multiple="false"
      :data="uptoken"
      :show-file-list="true"
      :on-change="OnChange"
      :on-success="OnSuccess"
      :before-upload="beforeUpload"
      :on-preview="handlePictureCardPreview"
      :auto-upload="false"
      :file-list="fileList"
      >
      <!-- <i class="el-icon-plus"></i> -->
      <el-button size="small" type="primary">{{Text.chooseFile}}</el-button>
      <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
    <!-- <el-progress v-if="showPercentage" v-show="percentage>0" :percentage="percentage" :status="uploadStatus"></el-progress> -->
  </div>
</template>
<script>
import moment from 'moment'
import { extname } from 'path'

import API from '@/API/index'

export default {
  name: 'uploader',
  props: [],
  data() {
    return {
      Text: {
        chooseFile: this.$t('uploader.chooseFile')
      },
      defaultAccept: 'image/*',
      // uploadStatus: '',
      // percentage: 0,
      drag: true,
      uptoken: {
        key: '',
        token: ''
      },
      fileList: [],
      outerHost: 'http://p6suk2a3h.bkt.clouddn.com',
      // showModal: false,
      // imageFile: '',
      dialogVisible: false,
      dialogImageUrl: ''
    }
  },
  computed: {
    computedData() {
      return Object.assign({}, this.data, this.uptoken)
    },
    computedVolumeLimit() {
      return this.volumeLimit != null ? this.volumeLimit : 1024 * 1024 * 20
    }
    // computedUrlSuffix() {
    //   return this.urlSuffix != null ? this.urlSuffix : '?imageView2/0/h/1080';
    // }
  },
  /* eslint-disable consistent-return */
  methods: {
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    beforeUpload(file) {
      const curr = moment()
        .format('YYYYMMDD')
        .toString()
      const prefix = `${moment(file.lastModified)
        .format('HHmmss')
        .toString()}${Date.now()}${parseInt(Math.random() * 100, 10)}`
      const suffix = extname(file.name)
      const key = encodeURI(`${curr}/${prefix}${suffix}`)

      if (this.computedVolumeLimit && file.size > this.computedVolumeLimit) {
        this.$message.error('请上传 20M 大小以内的文件')
        return false
      }

      this.uploadStatus = ''
      return API.GET_UPTOKEN({ filename: key, fsizeLimit: this.computedVolumeLimit })
        .then(({ data }) => {
          this.uptoken.key = key
          this.uptoken.token = data.data.upToken
          // if (typeof this.beforeUpload === 'function') {
          //   return this.beforeUpload(file)
          // }
        })
        .catch(() => {
          this.$message.error('获取 uptoken 失败')
        })
    },
    // eslint-disable-next-line
    OnChange(event, file, fileList) {
      // const self = this
      // this.percentage = event.percentage
      // if (this.percentage === 100) {
      //   setTimeout(() => {
      //     self.percentage = 0
      //   }, 3000)
      //   this.uploadStatus = 'success'
      // }
      if (event && event.status === 'ready') {
        // const supportCanvas = !!document.createElement('canvas').getContext
        // const ua = navigator.userAgent
        // const isSafari = ua.indexOf('Safari') > -1 && ua.indexOf('Chrome') === -1
        this.$refs.uploader.submit()
      }
      // if (typeof this.onChange === 'function') {
      //   return this.onChange(event, file, fileList)
      // }
    },
    // eslint-disable-next-line
    OnSuccess(response, file, fileList) {
      const { key } = response
      this.$emit('recieveNewImg', `${this.outerHost}/${key}`)
      this.$message({
        message: '头像上传成功',
        type: 'success'
      })
    }
  }
}
</script>
<style>
</style>
